<template>
	<div :style="styleExternalIcon" class="svg-external-icon svg-icon" v-if="isExternal" v-on="$listeners" />
	<svg :class="svgClass" aria-hidden="true" v-else v-on="$listeners">
		<use :xlink:href="iconName" />
	</svg>
</template>

<script>
const req = require.context('@', true, /\.svg$/) // 加载src下的所有svg文件
const requireAll = requireContext => {
	// 加载本地文件列表
	requireContext.keys().forEach(requireContext)
	// 返回文件列表
	return requireContext.keys()
}
requireAll(req)
export default {
	name: 'SvgIcon',
	props: {
		iconClass: {
			type: String,
			default: 'default'
		},
		className: {
			type: String,
			default: ''
		}
	},
	computed: {
		isExternal() {
			return this.iconClass && /^(https?:|mailto:|tel:)/.test(this.iconClass)
		},
		iconName() {
			return `#icon-${this.iconClass}`
		},
		svgClass() {
			if (this.className) {
				return 'svg-icon ' + this.className
			} else {
				return 'svg-icon'
			}
		},
		styleExternalIcon() {
			return this.iconClass
				? {
						mask: `url(${this.iconClass}) no-repeat 50% 50%`,
						'-webkit-mask': `url(${this.iconClass}) no-repeat 50% 50%`
				  }
				: {}
		}
	}
}
</script>

<style scoped>
.svg-icon {
	width: 1em;
	height: 1em;
	vertical-align: middle;
	fill: currentColor;
	overflow: hidden;
}

.svg-external-icon {
	background-color: currentColor;
	mask-size: cover !important;
	-webkit-mask-size: cover !important;
	display: inline-block;
}
</style>
